from django.db.models import Q
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from unicodedata import category

from course.models import Teacher, Course
from course.ser import TeacherSer, CourseSer
from home.models import CateModel
from home.ser import CategorySer, CateSer


# Create your views here.
class CategoryOne(APIView):
    def get(self, request):
        cate = CateModel.objects.filter(is_del=True, parent=None).order_by('order')
        data = CateSer(cate, many=True)
        return Response(data.data)


class CategoryTwo(APIView):
    def get(self, request):
        id = int(request.query_params.get('id'))
        if id != 0:
            cate = CateModel.objects.filter(is_del=True, parent=id).order_by('order')
        else:
            print(id)
            cate = CateModel.objects.exclude(parent=None, is_del=True).order_by('order')
        data = CateSer(cate, many=True)
        return Response(data.data)


class CoursePagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    max_page_size = 100
    page_query_param = 'page'


class CourseView(ListAPIView):
    serializer_class = CourseSer
    queryset = Course.objects.all()
    pagination_class = CoursePagination

    def get_queryset(self):
        query = Q()
        cate = int(self.request.query_params.get('cate'))
        direction = int(self.request.query_params.get('direction'))
        order = self.request.query_params.get('order')
        level = self.request.query_params.get('level')
        if cate != 0:
            query &= Q(is_del=False, category=cate)
        elif direction != 0:

            data = CateModel.objects.filter(parent=direction, is_del=True)

            cate = []
            for i in data:
                cate.append(i.id)
            print(cate)
            query &= Q(is_del=False, category__in=cate)

        if level:
            query &= Q(level=level)
        data = self.queryset.filter(query)
        if order:
            print(order)
            data = data.order_by(order)
        return data


class CourseById(APIView):
    def get(self, request):
        id = request.query_params.get('id')
        course = Course.objects.get(pk=id, is_del=False)
        courseser = CourseSer(course)
        return Response(courseser.data)
